import React, { useState, useEffect, useRef } from 'react';
import { View, TextInput, TouchableOpacity, FlatList, Text, StyleSheet, ActivityIndicator } from 'react-native';
import io from 'socket.io-client';
import api from '../services/api';

const ChatScreen = ({ route, navigation }) => {
  // 添加参数检查，提供默认值
  const { matchId, matchName } = route.params || {};
  const [messages, setMessages] = useState([]); // 初始化为空数组
  const [message, setMessage] = useState('');
  const [loading, setLoading] = useState(false);
  const [socket, setSocket] = useState(null); // 正确管理socket状态
  const flatListRef = useRef();

  useEffect(() => {
    const newSocket = io('http://10.0.2.2:3000'); // 确保地址正确
    setSocket(newSocket);

    newSocket.on('connect', () => {
      console.log('Socket connected');
    });

    newSocket.on('disconnect', () => {
      console.log('Socket disconnected');
    });

    // 接收消息 - 使用安全写法
    newSocket.on('new_message', (msg) => {
      console.log('收到消息:', msg);
      setMessages(prev => Array.isArray(prev) ? [...prev, msg] : [msg]);
    });

    // 只有在有matchId的情况下才获取历史消息
    if (matchId) {
      fetchMessages();
    }

    return () => {
      newSocket.disconnect();
    };
  }, [matchId]);

  useEffect(() => {
    // 滚动到底部
    if (messages.length > 0) {
      setTimeout(() => {
        flatListRef.current?.scrollToEnd({ animated: true });
      }, 100);
    }
  }, [messages]);

  const fetchMessages = async () => {
    setLoading(true);
    try {
      const response = await api.getMessages(matchId);
      // 确保设置的消息是数组类型
      const messagesData = response.messages || response || [];
      if (Array.isArray(messagesData)) {
        setMessages(messagesData);
      } else {
        setMessages([]);
      }
    } catch (error) {
      console.error('获取消息失败:', error);
      // 即使出错也确保消息数组是空数组而不是undefined
      setMessages([]);
    } finally {
      setLoading(false);
    }
  };

  const sendMessage = async () => {
    if (!message.trim() || !matchId || !socket) return;

    try {
      // 发送到服务器
      socket.emit('send_message', { 
        receiverId: matchId, 
        content: message,
        messageType: 'text'
      });

      // 添加到本地消息列表 - 使用安全写法
      const newMessage = {
        id: Date.now(), // 临时ID
        content: message,
        senderId: 'me', // 标记为自己发送
        sentAt: new Date().toISOString()
      };
      
      setMessages(prev => Array.isArray(prev) ? [...prev, newMessage] : [newMessage]);
      setMessage('');
    } catch (error) {
      console.error('发送消息失败:', error);
    }
  };

  // 跳转到新配对页面
  const goToNewMatches = () => {
    navigation.navigate('NewMatches');
  };

  const renderMessage = ({ item }) => {
    const isOwnMessage = item.senderId === 'me';
    
    return (
      <View style={[
        styles.messageContainer, 
        isOwnMessage ? styles.ownMessageContainer : styles.otherMessageContainer
      ]}>
        <View style={[
          styles.messageBubble, 
          isOwnMessage ? styles.ownMessageBubble : styles.otherMessageBubble
        ]}>
          <Text style={[
            styles.messageText, 
            isOwnMessage ? styles.ownMessageText : styles.otherMessageText
          ]}>
            {item.content}
          </Text>
          {item.sentAt && (
            <Text style={styles.messageTime}>
              {new Date(item.sentAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
            </Text>
          )}
        </View>
      </View>
    );
  };

  // 如果没有matchId参数，显示提示信息
  if (!matchId) {
    return (
      <View style={styles.container}>
        <View style={styles.header}>
          <Text style={styles.headerTitle}>聊天</Text>
          <TouchableOpacity style={styles.newMatchesButton} onPress={goToNewMatches}>
            <Text style={styles.newMatchesButtonText}>新配对</Text>
          </TouchableOpacity>
        </View>
        <View style={styles.emptyContainer}>
          <Text style={styles.emptyText}>请选择一个聊天对象</Text>
        </View>
      </View>
    );
  }

  return (
    <View style={styles.container}>
      <View style={styles.header}>
        <Text style={styles.headerTitle}>{matchName || '聊天'}</Text>
        <TouchableOpacity style={styles.newMatchesButton} onPress={goToNewMatches}>
          <Text style={styles.newMatchesButtonText}>新配对</Text>
        </TouchableOpacity>
      </View>

      {loading ? (
        <View style={styles.loadingContainer}>
          <ActivityIndicator size="large" color="#0000ff" />
        </View>
      ) : (
        <FlatList
          ref={flatListRef}
          data={messages}
          renderItem={renderMessage}
          keyExtractor={(item, index) => item.id?.toString() || index.toString()}
          style={styles.messagesList}
          contentContainerStyle={messages.length === 0 ? styles.emptyMessagesContainer : styles.messagesContainer}
          ListEmptyComponent={
            <View style={styles.emptyStateContainer}>
              <Text style={styles.emptyStateText}>还没有消息，开始聊天吧！</Text>
            </View>
          }
        />
      )}

      <View style={styles.inputContainer}>
        <TextInput
          value={message}
          onChangeText={setMessage}
          placeholder="输入消息..."
          style={styles.textInput}
          multiline
        />
        <TouchableOpacity 
          style={[styles.sendButton, !message.trim() && styles.sendButtonDisabled]} 
          onPress={sendMessage}
          disabled={!message.trim()}
        >
          <Text style={styles.sendButtonText}>发送</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f0f0f0'
  },
  header: {
    backgroundColor: '#2196F3',
    padding: 15,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center'
  },
  headerTitle: {
    color: 'white',
    fontSize: 18,
    fontWeight: 'bold'
  },
  newMatchesButton: {
    backgroundColor: 'rgba(255, 255, 255, 0.2)',
    paddingHorizontal: 10,
    paddingVertical: 5,
    borderRadius: 15
  },
  newMatchesButtonText: {
    color: 'white',
    fontSize: 14,
    fontWeight: 'bold'
  },
  connectionStatus: {
    color: 'white',
    fontSize: 12
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },
  messagesList: {
    flex: 1
  },
  messagesContainer: {
    padding: 10
  },
  emptyMessagesContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },
  messageContainer: {
    marginBottom: 10,
    flexDirection: 'row'
  },
  ownMessageContainer: {
    justifyContent: 'flex-end'
  },
  otherMessageContainer: {
    justifyContent: 'flex-start'
  },
  messageBubble: {
    maxWidth: '80%',
    padding: 10,
    borderRadius: 10
  },
  ownMessageBubble: {
    backgroundColor: '#2196F3',
    borderBottomRightRadius: 0
  },
  otherMessageBubble: {
    backgroundColor: 'white',
    borderBottomLeftRadius: 0
  },
  messageText: {
    fontSize: 16
  },
  ownMessageText: {
    color: 'white'
  },
  otherMessageText: {
    color: 'black'
  },
  messageTime: {
    fontSize: 10,
    color: '#999',
    textAlign: 'right',
    marginTop: 5
  },
  inputContainer: {
    flexDirection: 'row',
    padding: 10,
    backgroundColor: 'white',
    alignItems: 'flex-end'
  },
  textInput: {
    flex: 1,
    borderWidth: 1,
    borderColor: '#ccc',
    borderRadius: 20,
    paddingHorizontal: 15,
    paddingVertical: 10,
    maxHeight: 100,
    marginRight: 10
  },
  sendButton: {
    backgroundColor: '#2196F3',
    borderRadius: 20,
    paddingVertical: 10,
    paddingHorizontal: 20,
    justifyContent: 'center'
  },
  sendButtonDisabled: {
    backgroundColor: '#ccc'
  },
  sendButtonText: {
    color: 'white',
    fontWeight: 'bold'
  },
  emptyContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },
  emptyText: {
    fontSize: 16,
    color: '#666'
  },
  emptyStateContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20
  },
  emptyStateText: {
    fontSize: 16,
    color: '#666',
    textAlign: 'center'
  }
});

export default ChatScreen;